<template>
  <div>
    <el-dialog v-bind="$attrs" v-on="$listeners" :visible.sync="showDialog" @open="onOpen" @close="onClose"
               title="编辑用户">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="user" :rules="rules" size="medium" label-width="100px">
          <el-col :span="24">
            <!-- 用户头像 -->
            <el-form-item label="用户头像" prop="avatar" required>

              <!-- 头衔缩略图 -->
              <pan-thumb :image="user.avatar"/>
              <!-- 文件上传按钮 -->
              <el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">更换头像
              </el-button>

              <!--
                v-show：是否显示上传组件
                :key：类似于id，如果一个页面多个图片上传控件，可以做区分
                :url：后台上传的url地址
                @close：关闭上传组件
                @crop-upload-success：上传成功后的回调 -->
              <image-cropper
                v-show="imagecropperShow"
                :width="300"
                :height="300"
                :key="imagecropperKey"
                :url="'/uploadImgFile'"
                field="file"
                @close="closeImage"
                @crop-upload-success="cropSuccess"/>

<!--              <el-upload ref="avatar" :file-list="avatarfileList" :action="avatarAction"-->
<!--                         :before-upload="avatarBeforeUpload">-->
<!--                <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>-->
<!--              </el-upload>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item label="用户名" prop="username">
              <el-input v-model="user.username" placeholder="请输入用户名" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>

            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="user.nickname" placeholder="请输入昵称" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>

            <el-form-item label="手机号" prop="phoneNumber">
              <el-input v-model="user.phoneNumber" placeholder="请输入手机号" clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>

            <el-form-item label="生日" prop="birth">
              <el-date-picker v-model="user.birth" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                              :style="{width: '100%'}" placeholder="请选择生日" clearable></el-date-picker>
            </el-form-item>

          </el-col>

          <el-col :span="12">

            <el-form-item label="部门" prop="departmentId">
              <el-select v-model="user.departmentId" placeholder="请输入部门" clearable
                         :style="{width: '100%'}">
                <el-option
                  v-for="item in departments"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="user.sex" size="medium">
                <el-radio v-for="(item, index) in sexOptions" :key="index" :label="item.value"
                          :disabled="item.disabled">{{item.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="user.email" placeholder="请输入邮箱" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>

            <el-form-item label="密码" prop="password" v-if="user.id==null">
              <el-input v-model="user.password" placeholder="请输入密码" clearable show-password
                        :style="{width: '100%'}"></el-input>
            </el-form-item>

          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import ImageCropper from '../ImageCropper/index'
  import PanThumb from '../PanThumb/index'
  import {deleteImgFile} from "../../api/aliOss"
  import {saveUser,acquireUser,updateUser} from "../../api/users"
  import {findDeptAndCount} from '../../api/department'

    export default {
        name: 'UserAdd',
        inheritAttrs: false,
        components: {ImageCropper,PanThumb},
        props: {
            addOrUpdateVisible:{
                type: Boolean,
                default: false
            },
            userId: {
                type: Number,
                default: null
            },
            getUserList: {}
        },
        data() {
            return {
                user: {
                    avatar: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=421343706,2787877910&fm=26&gp=0.jpg',
                    username: undefined,
                    departmentId: undefined,
                    nickname: undefined,
                    sex: undefined,
                    password: undefined,
                    email: undefined,
                    phoneNumber: undefined,
                    birth: null,
                },
                // 控制弹出框显示隐藏
                showDialog:false,
                // 头像上传
                imagecropperShow: false, // 是否显示上传组件
                imagecropperKey: 0, // 上传组件id
                image: null,
                userImage: null,
                rules: {
                    username: [{
                        required: true,
                        message: '请输入用户名',
                        trigger: 'blur'
                    }],
                    departmentId: [{
                        required: true,
                        message: '请输入部门',
                        trigger: 'change'
                    }],
                    nickname: [{
                        required: true,
                        message: '请输入昵称',
                        trigger: 'blur'
                    }],
                    sex: [{
                        required: true,
                        message: '性别不能为空',
                        trigger: 'change'
                    }],
                    password: [{
                        required: true,
                        message: '请输入密码',
                        trigger: 'blur'
                    }],
                    email: [{
                        required: true,
                        message: '请输入邮箱',
                        trigger: 'blur'
                    }, {
                        pattern: /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/,
                        message: '请输入正确的邮箱格式',
                        trigger: 'blur'
                    }],
                    phoneNumber: [{
                        required: true,
                        message: '请输入手机号',
                        trigger: 'blur'
                    }, {
                        pattern: /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/,
                        message: '请输入正确的手机格式',
                        trigger: 'blur'
                    }],
                    birth: [{
                        required: true,
                        message: '请选择生日',
                        trigger: 'change'
                    }],
                },
                sexOptions: [{
                    "label": "帅哥",
                    "value": 0
                }, {
                    "label": "美女",
                    "value": 1
                }],
                departments: []
            }
        },
        computed: {},
        watch: {
            // 监听 addOrUpdateVisible 改变
            addOrUpdateVisible(oldVal,newVal){
                this.showDialog = this.addOrUpdateVisible
                if(this.userId!=null){
                    this.compileUser()
                }
            }
        },
        created() {
            this.getDeptAndCount()
        },
        mounted() {
        },
        methods: {
            onOpen() {
            },
            onClose() {
                this.$refs['elForm'].resetFields()
                this.$emit('changeShow', 'false')
            },
            close() {
                this.$emit('update:visible', false)
                this.$emit('changeShow', 'false')
            },
            handelConfirm() {
                this.$refs['elForm'].validate(valid => {
                    if (!valid) {
                        return
                    }
                    if(this.userId == null){
                        this.addUser()
                    }else {
                        this.updateUser()
                    }
                })
            },
            avatarBeforeUpload(file) {
                let isRightSize = file.size / 1024 / 1024 < 2
                if (!isRightSize) {
                    this.$message.error('文件大小超过 2MB')
                }
                return isRightSize
            },

            // 上传成功后的回调函数
            cropSuccess(data) {
                //获取上传前的图片
                var oldImage = this.image;
                this.imagecropperShow = false
                this.user.avatar = this.image = data.data.url;
                // 上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
                this.imagecropperKey = this.imagecropperKey + 1
                // 避免重复上传而不选择头像
                if(oldImage!=null){
                    console.log("2次后"+oldImage)
                    // 上传成功后删除之前的头像
                    this.deleteAvatar(oldImage);
                }
            },

            // 关闭上传组件
            closeImage() {
                this.imagecropperShow = false
                // 上传失败后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
                this.imagecropperKey = this.imagecropperKey + 1
            },
            //删除上传之前的图片
            async deleteAvatar(oldImage){
                const {data} = await deleteImgFile(oldImage)
                console.log("删除上传前的图片；"+data)
            },
            /*查询部门*/
            async getDeptAndCount() {
                const {data} = await findDeptAndCount()
                this.departments = data.data.departments
                // console.log(data.data.departments)
            },
            async addUser() {
                const {data: res } = await saveUser(this.user)
                if(res.code == 200){
                    this.$notify.success({
                        title: '操作成功',
                        message: '用户添加成功'
                    })
                    this.closePopUp()
                }else {
                    return this.$message.error('用户添加失败'+res.message)
                }
            },
            async updateUser() {
                const {data: res } = await updateUser(this.user)
                if(res.code == 200){
                    this.$notify.success({
                        title: '操作成功',
                        message: '用户信息修改成功'
                    })
                    this.deleteAvatar(this.userImage)
                    this.closePopUp()
                }else {
                    return this.$message.error('用户信息修改失败'+res.message)
                }
            },
            //编辑
            async compileUser(){
                const {data} = await acquireUser(this.userId)
                this.user = data.data.user;
                this.userImage = data.data.user.avatar;
                // console.log(data);
            },
            closePopUp(){
                //关闭
                this.userImage = null
                this.image = null
                this.user = {
                    avatar: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=421343706,2787877910&fm=26&gp=0.jpg',
                }
                //父组件刷新
                // this.$emit('getUserList');
                // this.$emit('getDeptAndCount');
                this.getUserList();
                this.$emit('changeShow', 'false')
            }
        }
    }

</script>
<style>
  .el-upload__tip {
    line-height: 1.2;
  }

</style>
